package com.cfweb.controller.service;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.jboss.resteasy.annotations.Form;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cfweb.api.BuildPackApi;
import com.cfweb.dao.CfEnvironmentMapper;
import com.cfweb.domain.CfEnvironment;
import com.cfweb.domain.CfEnvironmentExample;
import com.cfweb.util.ExtJSResponse;
import com.cfweb.util.FormUtil;


@Path("/buildpack")
@Produces(MediaType.APPLICATION_JSON)
@Service
public class BuildPackService {
	
	@Autowired
	private CfEnvironmentMapper environmentMapper;
	
	/**
     * session
     */
	@Autowired
	private HttpSession session;
	
	@GET
	@Path("/list")
	public ExtJSResponse getAppLogConfigs(){
		CfEnvironmentExample example=new CfEnvironmentExample();
		return ExtJSResponse.successResWithData(environmentMapper.selectByExample(example));
	}
	
	@POST
	@Path("/delete")
	public ExtJSResponse deleteAppLogConfigs(@FormParam("name") String name) throws Exception{
		CfEnvironmentExample example=new CfEnvironmentExample();
		example.createCriteria().andEnvNameEqualTo(name);
		BuildPackApi.delete_buildpack(session, name);
		return ExtJSResponse.successResWithData(environmentMapper.deleteByExample(example));
	}
	
	@POST
	@Path("/addBuildpack")
	@Consumes("multipart/form-data")
	public ExtJSResponse addAppLogConfigs(MultipartFormDataInput dataInput) throws Exception{
		Map<String, List<InputPart>> uploadForm = dataInput.getFormDataMap();
		List<InputPart> fileParts = uploadForm.get("uploadFile");
		String envName = FormUtil.getFormString(uploadForm.get("envName"));
//		String position = FormUtil.getFormString(uploadForm.get("position"));
		File file = null;
		if (fileParts != null && !fileParts.isEmpty()) {
			InputPart inputPart = fileParts.get(0);
			InputStream inputStream = inputPart.getBody(InputStream.class, null);
			file = new File(envName+".zip");
			FormUtil.inputstreamtofile(inputStream, file);
		}
		
		if(file==null){
			 ExtJSResponse.errorResWithMsg("please select a file");
		}
		
		BuildPackApi.createBuildpack(envName, new File("/home/yufangjiang/Documents/cfweb_deploy/buildpack/java-buildpack-offline-a6cef1b-test.zip"), 0, session);	
		CfEnvironment environment=new CfEnvironment();
		environment.setEnvName(envName);
		return ExtJSResponse.successResWithData(environmentMapper.insert(environment));
	}
}
